import { routerRedux } from 'dva/router';
import {bankInfo, fakeAccountLogin} from '../services/api';
import { setAuthority } from '../utils/authority';
import { reloadAuthorized } from '../utils/Authorized';

export default {
    namespace: 'login',

    state: {
        status: undefined,
    },

    effects: {
        * login({ payload, callback }, { call, put }) {
            // setAuthority(['admin'])
            // return;
            const response = yield call(fakeAccountLogin, payload);
            // Login successfully
            yield put({
                type: 'changeLoginStatus',
                payload: response,
            });

            if (response.code === 20000) {
                reloadAuthorized();
                sessionStorage.setItem('token', response.data.access_token);
                yield put(routerRedux.push('/'));
            }
            callback(response);
        },
        * logout(_, { put, select }) {
            try {
                // get location pathname
                const urlParams = new URL(window.location.href);
                const pathname = yield select(state => state.routing.location.pathname);
                // add the parameters in the url
                urlParams.searchParams.set('redirect', pathname);
                window.history.replaceState(null, 'login', urlParams.href);
            } finally {
                yield put({
                    type: 'changeLoginStatus',
                    payload: {
                        status: false,
                        access_token: 'guest',
                    },
                });
                reloadAuthorized();
                yield put(routerRedux.push('/user/login'));
            }
        },

    },

    reducers: {
        changeLoginStatus(state, { payload }) {
            if (typeof (payload.data) !== 'undefined' && payload.data !== null) {
                setAuthority(payload.data.roles);
            }
            if (payload.code !== 20000) {
                return {
                    ...state,
                    status: 'error',
                    type: 'account',
                };
            }
            return {
                ...state,
                status: payload.code,
                type: payload.type,
            };
        },
    },
};
